<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Constants\RoomInviteSendTaskStatusConstants;
use App\CustHub\Mapper\ChRoomInviteSendTaskMapper;
use App\CustHub\Model\ChRoomInviteSendTask;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\SendRobotMessageService;
use Carbon\Carbon;
use Mine\Abstracts\AbstractService;
use function Hyperf\Collection\data_get;

class ChRoomInviteSendTaskService extends AbstractService
{
    public $mapper;

    public function __construct(ChRoomInviteSendTaskMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 检查是否已存在待发送任务
     * @param string $roomWxid
     * @param array $userId
     * @return void
     */
    public function check(string $roomWxid,array $userId): void
    {
        $this->checkInviteMessages($roomWxid,$userId);
        $this->checkMarketingMessages($roomWxid,$userId);
    }

    /**
     * 检查是否已存在待重发任务
     * @param string $roomWxid
     * @param array $userId
     * @return void
     */
    private function checkInviteMessages(string $roomWxid,array $userId): void
    {
        if($this->mapper->checkReSendTaskExistence($roomWxid,$userId)){
            $this->mapper->model::query()
                ->whereIn('user_id',$userId)
                ->where('room_wxid',$roomWxid)
                ->where('status',RoomInviteSendTaskStatusConstants::WAITING)
                ->where('type',0)
                ->update(['status'=>RoomInviteSendTaskStatusConstants::CANCELLED]);
        }
    }


    /**
     * 检查是否已存在待发送营销消息
     * @param string $roomWxid
     * @param array $userId
     * @return void
     */
    private function checkMarketingMessages(string $roomWxid,array $userId): void
    {
        $list = $this->mapper->getMarketingMessages($roomWxid,$userId);

        foreach ($list as $item){
            $extra = $item->extra;
            $sendTime = Carbon::now()->addDays($extra['day'])->addHours($extra['hour'])->addMinutes($extra['minute'])->timestamp;
            $item->send_time = $sendTime;
            $item->save();
        }
    }


    /**
     * 定时任务-处理
     * @return void
     */
    public function timedMessageHandler()
    {
        $list = ChRoomInviteSendTask::query()
            ->where('send_time','<=',time())
            ->where('send_time','<>',0)
            ->where('status',RoomInviteSendTaskStatusConstants::WAITING)
            ->get();

        foreach ($list as $item){
            $item->status = RoomInviteSendTaskStatusConstants::COMPLETED;
            $item->save();
            if($item->type == 0){
                $sendInvite = [
                    'msg_type' => 'crowd',
                    'robot_id' => $item->robot_id,
                    'to_id' => $item->room_wxid,
                    'content' => [
                        'member_list' => [$item->user_id]
                    ]
                ];
                $this->sendMessage($sendInvite);
            }
            $msgLimit = 0;
            foreach ($item->content as $guideTextItem){
                $extra = data_get($guideTextItem,'extra.limit',[]);
                //单位  1秒 2分钟
                $unit = data_get($extra,'unit',1);
                $limit = data_get($extra,'value',0);
                if($unit == 2){
                    $limit = $limit * 60;
                }elseif ($unit == 3){
                    $limit = $limit * 60 * 60;
                }
                $msgLimit = $msgLimit + $limit;

                $messageData = [
                    'robot_id' => $item->robot_id,
                    'to_id' => $item->user_id,
                    'msg_type' => $guideTextItem['msg_type'],
                    'content' => $guideTextItem['content']
                ];
                $this->sendMessage($messageData,$msgLimit);
            }
        }

    }

    /**
     * 发送消息
     * @param array $data
     * @param int $delayTime
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    private function sendMessage(array $data,int $delayTime = 0): void
    {
        container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
            classname: SendRobotMessageService::class,
            method: 'handle',
            data: $data
        )),$delayTime);
    }

}